import { WebSocket, WebSocketServer } from 'ws';
import { logger } from '../utils/logger';

interface WebSocketMessage {
  type: string;
  data: any;
}

class WebSocketService {
  private static wss: WebSocketServer;
  private static clients: Set<WebSocket> = new Set();

  public static initialize(server: any) {
    this.wss = new WebSocketServer({ server });
    
    this.wss.on('connection', (ws: WebSocket) => {
      this.clients.add(ws);
      logger.info('New WebSocket client connected');

      ws.on('close', () => {
        this.clients.delete(ws);
        logger.info('WebSocket client disconnected');
      });

      ws.on('error', (error) => {
        logger.error('WebSocket error:', error);
        this.clients.delete(ws);
      });
    });
  }

  public static broadcast(message: WebSocketMessage) {
    const messageStr = JSON.stringify(message);
    this.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(messageStr);
      }
    });
  }
}

export { WebSocketService }; 